<?php
namespace Wechat;

class SubscribeMessage
{

    public function sendSubMessage($param, $openId, $tmpl = '', $data, $page = 'index', $miniprogram_state = 'formal')
    {

        $params['touser']            = $openId;
        $params['template_id']       = $tmpl;
        $params['page']              = $page;
        $params['miniprogram_state'] = $miniprogram_state;
        $params['data']              = $data;
        $token                       = $this->getAccessToken($param);
        $url                         = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $token;
        $re                          = $this->curl_url($url, $params);
        return $re;

    }
    public function getAccessToken($param)
    {
        $url  = sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", $param['appid'], $param['app_secret']);
        $info = file_get_contents($url); //发送HTTPs请求并获取返回的数据，推荐使用curl
        $json = json_decode($info); //对json数据解码
        $arr  = get_object_vars($json);
        if (!array_key_exists('errcode', $arr)) {
            return $arr['access_token'];
        }
        file_put_contents('get_access_token_error.txt', var_export($arr, true) . PHP_EOL, FILE_APPEND);
    }
    private function curl_url($url, $json)
    {
        $body    = json_encode($json);
        $headers = array("Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }
}
